package com.tenglong.teacher.ui.homework.msgviewholder;

import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.netease.nim.uikit.business.session.audio.MessageAudioControl;
import com.netease.nim.uikit.common.media.audioplayer.Playable;
import com.netease.nim.uikit.common.util.sys.ScreenUtil;
import com.netease.nim.uikit.common.util.sys.TimeUtil;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.AudioAttachment;
import com.netease.nimlib.sdk.msg.constant.AttachStatusEnum;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.HomeWorkIM;
import com.vincan.medialoader.DownloadManager;
import com.vincan.medialoader.MediaLoader;
import com.vincan.medialoader.download.DownloadListener;

import java.io.File;

import static com.tenglong.teacher.ui.homework.msgviewholder.MsgViewHolderAudio.CLICK_TO_PLAY_AUDIO_DELAY;

public class HWAudioViewHolder extends HWBaseViewHolder implements DownloadListener {
    private TextView durationLabel;
    private View containerView;

    private ImageView animationView;

    private MessageAudioControl audioControl;

    public HWAudioViewHolder(View itemView) {
        super(itemView);
        durationLabel = itemView.findViewById(R.id.message_item_audio_duration);
        containerView = itemView.findViewById(R.id.message_item_audio_container);
        animationView = itemView.findViewById(R.id.message_item_audio_playing_animation);
        animationView.setBackgroundResource(0);
        audioControl = MessageAudioControl.getInstance(mContext);
    }

    private String downLoadAudio() {
        if (message instanceof HomeWorkIM) {
            if (!MediaLoader.getInstance(mContext).isCached(((AudioAttachment) message.getAttachment()).getUrl())) {
                DownloadManager.Request request = new DownloadManager.Request(((AudioAttachment) message.getAttachment()).getUrl());
                DownloadManager.getInstance(mContext).enqueue(request, this);
                return null;
            } else {
                File file = MediaLoader.getInstance(mContext).getCacheFile(((AudioAttachment) message.getAttachment()).getUrl());
                return file.getAbsolutePath();
            }
        }
        return null;
    }

    public void onBindViewHolder(IMMessage msg) {
        super.onBindViewHolder(msg);
        downLoadAudio();
        setGravity(animationView, Gravity.LEFT | Gravity.CENTER_VERTICAL);
        setGravity(durationLabel, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        containerView.setBackgroundResource(NimUIKitImpl.getOptions().messageLeftBackground);
        containerView.setPadding(ScreenUtil.dip2px(15), ScreenUtil.dip2px(8), ScreenUtil.dip2px(10), ScreenUtil.dip2px(8));
        animationView.setBackgroundResource(com.netease.nim.uikit.R.drawable.nim_audio_animation_list_left);
        durationLabel.setTextColor(Color.BLACK);
        final AudioAttachment msgAttachment = (AudioAttachment) msg.getAttachment();
        long duration = msgAttachment.getDuration();
        setAudioBubbleWidth(duration);
        durationLabel.setTag(msg.getUuid());
        if (!isMessagePlaying(audioControl, msg)) {
            if (audioControl.getAudioControlListener() != null &&
                    audioControl.getAudioControlListener().equals(onPlayListener)) {
                audioControl.changeAudioControlListener(null);
            }
            updateTime(duration);
            stop();
        } else {
            audioControl.changeAudioControlListener(onPlayListener);
            play();
        }
    }

    private void setAudioBubbleWidth(long milliseconds) {
        long seconds = TimeUtil.getSecondsByMilliseconds(milliseconds);
        int currentBubbleWidth = calculateBubbleWidth(seconds, NimUIKitImpl.getOptions().audioRecordMaxTime);
        ViewGroup.LayoutParams layoutParams = containerView.getLayoutParams();
        layoutParams.width = currentBubbleWidth;
        containerView.setLayoutParams(layoutParams);
    }

    private int calculateBubbleWidth(long seconds, int MAX_TIME) {
        int maxAudioBubbleWidth = getAudioMaxEdge();
        int minAudioBubbleWidth = getAudioMinEdge();

        int currentBubbleWidth;
        if (seconds <= 0) {
            currentBubbleWidth = minAudioBubbleWidth;
        } else if (seconds > 0 && seconds <= MAX_TIME) {
            currentBubbleWidth = (int) ((maxAudioBubbleWidth - minAudioBubbleWidth) * (2.0 / Math.PI)
                    * Math.atan(seconds / 10.0) + minAudioBubbleWidth);
        } else {
            currentBubbleWidth = maxAudioBubbleWidth;
        }

        if (currentBubbleWidth < minAudioBubbleWidth) {
            currentBubbleWidth = minAudioBubbleWidth;
        } else if (currentBubbleWidth > maxAudioBubbleWidth) {
            currentBubbleWidth = maxAudioBubbleWidth;
        }

        return currentBubbleWidth;
    }

    private void updateTime(long milliseconds) {
        long seconds = TimeUtil.getSecondsByMilliseconds(milliseconds);
        if (seconds >= 0) {
            durationLabel.setText(seconds + "\"");
        } else {
            durationLabel.setText("");
        }
    }

    protected boolean isMessagePlaying(MessageAudioControl audioControl, IMMessage message) {
        if (audioControl.getPlayingAudio() != null && audioControl.getPlayingAudio().isTheSame(message)) {
            return true;
        } else {
            return false;
        }
    }

    public static int getAudioMaxEdge() {
        return (int) (0.6 * ScreenUtil.screenMin);
    }

    public static int getAudioMinEdge() {
        return (int) (0.1875 * ScreenUtil.screenMin);
    }

    protected void onItemClick(View v) {
        if (audioControl != null) {
            if (message instanceof HomeWorkIM) {
                String path = downLoadAudio();
                if (path != null) {
                    initPlayAnim(); // 设置语音播放动画
                    audioControl.startPlayAudioDelay(CLICK_TO_PLAY_AUDIO_DELAY, message, onPlayListener, path);
                }
            } else {
                if (message.getDirect() == MsgDirectionEnum.In && message.getAttachStatus() != AttachStatusEnum.transferred) {
                    if (message.getAttachStatus() == AttachStatusEnum.fail || message.getAttachStatus() == AttachStatusEnum.def) {
                        NIMClient.getService(MsgService.class).downloadAttachment(message, false);
                    }
                }
                initPlayAnim(); // 设置语音播放动画
                audioControl.startPlayAudioDelay(CLICK_TO_PLAY_AUDIO_DELAY, message, onPlayListener);
                return;
            }
        }
    }

    private boolean isTheSame(String uuid) {
        String current = durationLabel.getTag().toString();
        return !TextUtils.isEmpty(uuid) && uuid.equals(current);
    }

    private MessageAudioControl.AudioControlListener onPlayListener = new MessageAudioControl.AudioControlListener() {

        @Override
        public void updatePlayingProgress(Playable playable, long curPosition) {
            if (!isTheSame(message.getUuid())) {
                return;
            }
            if (curPosition > playable.getDuration()) {
                return;
            }
            updateTime(curPosition);
        }

        @Override
        public void onAudioControllerReady(Playable playable) {
            if (!isTheSame(message.getUuid())) {
                return;
            }
            play();
        }

        @Override
        public void onEndPlay(Playable playable) {
            if (!isTheSame(message.getUuid())) {
                return;
            }
            updateTime(playable.getDuration());
            stop();
        }
    };

    private void play() {
        if (animationView.getBackground() instanceof AnimationDrawable) {
            AnimationDrawable animation = (AnimationDrawable) animationView.getBackground();
            animation.start();
        }
    }

    private void stop() {
        if (animationView.getBackground() instanceof AnimationDrawable) {
            AnimationDrawable animation = (AnimationDrawable) animationView.getBackground();
            animation.stop();
            endPlayAnim();
        }
    }

    private void initPlayAnim() {
        animationView.setBackgroundResource(com.netease.nim.uikit.R.drawable.nim_audio_animation_list_left);
    }

    private void endPlayAnim() {
        animationView.setBackgroundResource(com.netease.nim.uikit.R.drawable.nim_audio_animation_list_left_3);
    }

    @Override
    public void onProgress(String url, File file, int progress) {
        if (progress == 100) {
            ((AudioAttachment) message.getAttachment()).setPath(file.getAbsolutePath());
        }
    }

    @Override
    public void onError(Throwable e) {
    }
}
